﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LybrixNursingCommon;
using LybrixNursingCRMDesktop.FrameWork;
using LybrixNursingCRMDesktop.CustomControls;
using Microsoft.Win32;
using System.IO;
using LybrixNursingCRMDesktop.Windows;

namespace LybrixNursingCRMDesktop
{
    /// <summary>
    /// Interaction logic for Prospect.xaml
    /// </summary>
    /// 
   
    public partial class ProspectPage : Page
    {
        private NursingDBContainer _entities;
        string _currentCust;
        customer currentCustomer;
        PaymentHeader currentPaymentHeader;
        TeekDocs currentDoc;
        bool isNew = true;
        List<Teek_Contact> contacts = new List<Teek_Contact>();
        int currentContactCard = 0;

        public ProspectPage()
        {

            InitializeComponent();

  
            _entities = Repository.Entities;
            OpenFileDate.SelectedDate = DateTime.Now;
            _currentCust = GetUniqueID();
            ProspectID.Content = _currentCust;
            intializComboboxes();
            isNew = true;
            this.Loaded += new RoutedEventHandler(ProspectPage_Loaded);
            secondTab.Visibility = System.Windows.Visibility.Hidden;
            FourthTab.Visibility = System.Windows.Visibility.Hidden;
            PassOverDate.Visibility = System.Windows.Visibility.Hidden;
            PassOverLabel.Visibility = System.Windows.Visibility.Hidden;
            homeChoices.Visibility = System.Windows.Visibility.Hidden;
            currLocation.Visibility = System.Windows.Visibility.Hidden;
            currLocationLabel.Visibility = System.Windows.Visibility.Hidden;
        }

        public ProspectPage(customer _customer)
        {

            InitializeComponent();


            _entities = Repository.Entities;
            intializComboboxes();

            isNew = false;
            currentCustomer = _customer;
            initTeek();
            this.Loaded += new RoutedEventHandler(ProspectPage_Loaded);
            secondTab.Visibility = System.Windows.Visibility.Visible;
            if (currentCustomer.Teek.status == "4")
            {
                mainTab.IsEnabled = false;
                CloseOpenTeek.Content = FindResource("Open");
            }
            else
            {
                mainTab.IsEnabled = true;
                CloseOpenTeek.Content = FindResource("Close");
            }


            if(!(bool)Login.loggedUser.isSuperUser)
                FourthTab.Visibility = System.Windows.Visibility.Hidden;
        }


        private void initTeek()
        {

            ProspectID.Content = currentCustomer.custNumber;
            FirstName.Text = currentCustomer.firstName;
            FamilyName.Text = currentCustomer.lastName;
            ID.Text = currentCustomer.socialID;
            Age.Text = (currentCustomer.age).ToString() ;
            OpenFileDate.SelectedDate = currentCustomer.teekOpen_date;
            ControllerDate.SelectedDate = currentCustomer.Teek.follow_date;
            sendEmail.IsChecked = currentCustomer.Teek.sendEmail;
            SendSMS.IsChecked = currentCustomer.Teek.sendSMS;
            FamilyStatus.Text = currentCustomer.familyStatus_descr;
            FamilyStatus.SelectedItem = GetItem(FamilyStatus, currentCustomer.familyStatus_descr);
            Status.Text = currentCustomer.status_descr;
            Status.SelectedItem = GetItem(Status, currentCustomer.status_descr);
            CurrentLocation.Text = currentCustomer.location_descr;
            CurrentLocation.SelectedItem = GetItem(CurrentLocation, currentCustomer.location_descr);

           
            

             cmbCustStatus.Text = currentCustomer.Teek.Teekstatus_descr;
             cmbCustStatus.SelectedItem = GetItem(cmbCustStatus, currentCustomer.Teek.Teekstatus_descr);


            if (currentCustomer.status_descr == "נפטר/ה")
            {
                PassOverLabel.Visibility = System.Windows.Visibility.Visible;
                PassOverDate.Visibility = System.Windows.Visibility.Visible;
                PassOverDate.SelectedDate = currentCustomer.pass_date;
            }
            else
            {
                PassOverLabel.Visibility = System.Windows.Visibility.Hidden;
                PassOverDate.Visibility = System.Windows.Visibility.Hidden;
            }
            if (currentCustomer.location_descr == "בית")
            {
                homeChoices.ISliveAlone = currentCustomer.livesAlone;
                homeChoices.ISlivesWithFamily = currentCustomer.livesWithfamily;
                homeChoices.ISlivesWithPartner = currentCustomer.livesWithPartner;
                homeChoices.IShasAssistance = currentCustomer.hasAssistance;
                homeChoices.IShasforignAssistance = currentCustomer.hasForignAssistance;
                homeChoices.ISbayetMotam = currentCustomer.isBayetMotam;
                if (currentCustomer.isBayetMotam)
                    homeChoices.ISXbayetMotam = false;
                else
                    homeChoices.ISXbayetMotam = true;

                homeChoices.ISstairs = currentCustomer.hasStairs;
                homeChoices.ISElivator = currentCustomer.hasElevator;
                currLocationLabel.Visibility = System.Windows.Visibility.Hidden;
                currLocation.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                if (currentCustomer.location_descr == "בית חולים" || currentCustomer.location_descr == "שיקום")
                {
                    currLocationLabel.Visibility = System.Windows.Visibility.Visible;
                    currLocation.Visibility = System.Windows.Visibility.Visible;
                    currLocation.Text = currentCustomer.cameFrom;

                }
                

                homeChoices.Visibility = System.Windows.Visibility.Hidden;
            }

            FlowDocument doc = new FlowDocument();

            additionalInfo.Document.Blocks.Clear();
            additionalInfo.Document.Blocks.Add(new Paragraph(new Run(currentCustomer.Teek.additionalInfo)));
            ProspectStatusSelect.Text = currentCustomer.Teek.status_descr;
            ProspectStatusSelect.SelectedItem = GetItem(ProspectStatusSelect, currentCustomer.Teek.status_descr);
            ControllerID.SelectedItem = currentCustomer.Teek.agent;
            if (!(bool)Login.loggedUser.isSuperUser && !(bool)Login.loggedUser.isAdmin)
            {
                ControllerID.IsEnabled = false;
            }

           
            Sapak.SelectedItem = currentCustomer.Teek.Sapak;
            cmbBateAvot.SelectedItem = currentCustomer.Teek.NursingHome;
            initContacts();
            if (!(bool)Login.loggedUser.isSuperUser)
                FourthTab.Visibility = System.Windows.Visibility.Hidden;
            else
                FourthTab.Visibility = System.Windows.Visibility.Visible;
        }


        private void initContacts()
        {
            List<TeekContacts>  tmpcontacts = null; 
            tmpcontacts = currentCustomer.Teek.TeekContacts.ToList<TeekContacts>();
            foreach(TeekContacts _contact in tmpcontacts)
            {
                Teek_Contact tmpcontact = new Teek_Contact();
                tmpcontact.Id = (_contact.Id).ToString();
                tmpcontact.Address = _contact.address;
                tmpcontact.Name = _contact.contactName;
                tmpcontact.Phone =  _contact.phone;
                tmpcontact.Mobile = _contact.mobile;
                tmpcontact.Is_primary = (bool)_contact.is_primary;
                tmpcontact.Is_synched = true;
                tmpcontact.Is_family = (bool)_contact.is_family;
                tmpcontact.Is_aptropos = (bool)_contact.is_apotrobs;
                contacts.Add(tmpcontact);

            }

            if(contacts.Count > 0)
            {
                card.Nurse1.Value = contacts[0].Name;
                card.Address.Text = contacts[0].Address;
                card.Phoen1.Value = contacts[0].Phone;
                card.Phoen2.Value = contacts[0].Mobile;
                card.family.IsChecked = contacts[0].Is_family;
                card.aptrops.IsChecked = contacts[0].Is_primary;
                card.primary.IsChecked = contacts[0].Is_aptropos;
                card.IsAddedToList = true;
            }
        }

        private ComboboxItem GetItem(ComboBox combo , string value)
        {
            ComboboxItem _item = null;

            for (int i = 0; i < combo.Items.Count; ++i)
            {
                if (((ComboboxItem)(combo.Items[i])).Descr == value)
                {
                    _item = (ComboboxItem)combo.Items[i];
                    break;
                }
                    
            }

                return _item;
        }

        private void intializComboboxes()
        {
            FamilyStatus.ItemsSource = null;
            Status.ItemsSource = null;
            CurrentLocation.ItemsSource = null;
            ProspectStatusSelect.ItemsSource = null;
            ControllerID.ItemsSource = null;
            Sapak.ItemsSource = null;
            cmbCustStatus.ItemsSource = null;

            Sapak.ItemsSource = _entities.Sapaks.ToList<Sapak>();

            Sapak.DisplayMemberPath = "sapakName";
            Sapak.SelectedValuePath = "Id";

            //SapakType.ItemsSource = new List<ComboboxItem> { 
            //    new ComboboxItem( "-1",""), 
            //    new ComboboxItem("1","זמני"), 
            //    new ComboboxItem("2","קבוע") 
            //};

            cmbCustStatus.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","עדיין לא נקלט"), 
                new ComboboxItem("2","נקלט"), 
                new ComboboxItem("3","נקלט עם קוד")
            };
            cmbCustStatus.DisplayMemberPath = "Descr";
            cmbCustStatus.SelectedValuePath = "Id";

            FamilyStatus.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","רווק"), 
                new ComboboxItem("2","נשוי"), 
                new ComboboxItem("3","גרוש/ה"), 
                new ComboboxItem("4","אלמן/ה") 
            };
            FamilyStatus.DisplayMemberPath = "Descr";
            FamilyStatus.SelectedValuePath = "Id";
            Status.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem("-1", ""), 
                new ComboboxItem("1", "עצמאי/ת"), 
                new ComboboxItem("2", "תשוש גוף"), 
                new ComboboxItem("3", "סיעודי דימנטי"), 
                new ComboboxItem("4", "סיעודי") ,
                new ComboboxItem("5", "סיעודי מורכב") ,
                new ComboboxItem("6", "נפטר/ה") ,
                new ComboboxItem("7", "תשוש נפש") ,
                new ComboboxItem("8", "לא ידוע") 
            };
            Status.DisplayMemberPath = "Descr";
            Status.SelectedValuePath = "Id";
            CurrentLocation.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","בית חולים"), 
                new ComboboxItem("2","שיקום"), 
                new ComboboxItem("3","בית")
            };
            CurrentLocation.DisplayMemberPath = "Descr";
            CurrentLocation.SelectedValuePath = "Id";

            ProspectStatusSelect.ItemsSource = new List<ComboboxItem> { 
                new ComboboxItem( "-1",""), 
                new ComboboxItem("1","חדש"), 
                new ComboboxItem("2","בטיפול"), 
                new ComboboxItem("3","נקלט"), 
                new ComboboxItem("4","סגור")
            };
            ProspectStatusSelect.DisplayMemberPath = "Descr";
            ProspectStatusSelect.SelectedValuePath = "Id";


            ControllerID.ItemsSource = _entities.agents.ToList<agent>();
            ControllerID.DisplayMemberPath = "firstName";
            ControllerID.SelectedValuePath = "Id";

            cmbBateAvot.ItemsSource = _entities.NursingHomes.ToList<NursingHome>();
            cmbBateAvot.DisplayMemberPath = "HomeName";
            cmbBateAvot.SelectedValuePath = "Id";


        }
        void ProspectPage_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void LoadProspectPage()
        {
          
        }

        private void ToolBar_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void onSave_Click(object sender, RoutedEventArgs e)
        {
            customer cust = null;
            Teek teek = null;
            


            if (isNew)
            {
                teek = CheckIfCustomerExists(_currentCust);
                if (teek == null)
                {
                    cust = new customer();
                    teek = new Teek();
                    cust.custNumber = _currentCust;
                    secondTab.Visibility =  System.Windows.Visibility.Hidden;
                }
                else
                {
                    cust = teek.customer;
                    currentCustomer = cust;
                    initTeek();
                    isNew = false;
                    secondTab.Visibility = System.Windows.Visibility.Visible;
                }
            }
            else
            {
                cust = currentCustomer;
                teek = currentCustomer.Teek;
                secondTab.Visibility = System.Windows.Visibility.Visible;
            }


            short custAge = 0;
            string cust_location = "0";


            string infoText = new TextRange(additionalInfo.Document.ContentStart, additionalInfo.Document.ContentEnd).Text;

            if (OpenFileDate.SelectedDate == null)
            {
                MessageBox.Show("תאריך פתיחת תיק חסר !", "שגיאה", MessageBoxButton.OK);
                return;
            }
            teek.additionalInfo = infoText;
            teek.agent = (agent)(ControllerID.SelectedItem);
            teek.sendSMS = (Boolean)SendSMS.IsChecked;
            teek.sendEmail = (Boolean)sendEmail.IsChecked;
            teek.Sapak = (Sapak)(Sapak.SelectedItem);

            if (cmbCustStatus.SelectedItem != null)
            {
                teek.Teekstatus = ((ComboboxItem)(cmbCustStatus.SelectedItem)).Id;
                teek.Teekstatus_descr = ((ComboboxItem)(cmbCustStatus.SelectedItem)).Descr;
            }
            else
            {
                teek.Teekstatus = "-1";
                teek.Teekstatus_descr = string.Empty;
            }

            teek.NursingHome = (NursingHome)(cmbBateAvot.SelectedItem);


            if (ControllerDate.SelectedDate != null)
                teek.follow_date = ControllerDate.SelectedDate;

            if (((ComboboxItem)(ProspectStatusSelect.SelectedItem)) != null)
            {
                teek.status = ((ComboboxItem)(ProspectStatusSelect.SelectedItem)).Id;
                teek.status_descr = ((ComboboxItem)(ProspectStatusSelect.SelectedItem)).Descr;
            }
            else
            {
                   teek.status = "-1";
                   teek.status_descr = string.Empty;
            }
            
            if (isNew)
            {
                _entities.AddToTeeks(teek);
            }




            if (!short.TryParse(Age.Text, out custAge))
            {
                MessageBox.Show("הגיל שהזנתה לא חוקי", "שגיאה", MessageBoxButton.OK);
                return;
            }
            else
            {
                if (custAge <= 0)
                {
                    MessageBox.Show("הגיל לא יכול להיות שלילי או 0", "שגיאה", MessageBoxButton.OK);
                    return;
                }
                else
                    cust.age = custAge;
            }
            cust.firstName = FirstName.Text;
            cust.lastName = FamilyName.Text;
            cust.socialID = ID.Text;
            cust.teekOpen_date = (DateTime)OpenFileDate.SelectedDate;
 
            if (cust.status_descr == "נפטר/ה")
            {
                cust.pass_date = (DateTime)PassOverDate.SelectedDate;
            }


            if (FamilyStatus.SelectedItem != null)
            {
                cust.familyStatus = ((ComboboxItem)(FamilyStatus.SelectedItem)).Id;
                cust.familyStatus_descr = ((ComboboxItem)(FamilyStatus.SelectedItem)).Descr;
            }
            else
            {
                cust.familyStatus =  "-1";
                cust.familyStatus_descr = string.Empty;
            }


            if (Status.SelectedItem != null)
            {

                cust.status = ((ComboboxItem)(Status.SelectedItem)).Id;
                cust.status_descr = ((ComboboxItem)(Status.SelectedItem)).Descr;
            }
            else
            {

                cust.status = "-1";
                cust.status_descr = string.Empty;
            }

            if (CurrentLocation.SelectedItem != null)
            {

                cust_location = ((ComboboxItem)(CurrentLocation.SelectedItem)).Id;
                if (cust_location == "3")
                {
                    cust.isBayetMotam = homeChoices.ISbayetMotam;
                    cust.livesAlone = homeChoices.ISliveAlone;
                    cust.livesWithfamily = homeChoices.ISlivesWithFamily;
                    cust.livesWithPartner = homeChoices.ISlivesWithPartner;
                    cust.hasStairs = homeChoices.ISstairs;
                    cust.hasForignAssistance = homeChoices.IShasforignAssistance;
                    cust.hasElevator = homeChoices.ISElivator;
                    cust.hasAssistance = homeChoices.IShasAssistance;
                }
                else
                {
                    if (cust_location == "1" || cust_location == "2")
                    {
                        cust.cameFrom = currLocation.GetValue();
                    }
                    cust.isBayetMotam = false;
                    cust.livesAlone = false;
                    cust.livesWithfamily = false;
                    cust.livesWithPartner = false;
                    cust.hasStairs = false;
                    cust.hasForignAssistance = false;
                    cust.hasElevator = false;
                    cust.hasAssistance = false;
                }

                cust.location = cust_location;
                cust.location_descr = ((ComboboxItem)(CurrentLocation.SelectedItem)).Descr;

            }
            else
            {
                cust.location = "-1";
                cust.location_descr = string.Empty;
            }

            teek.customer = cust;
            cust.teekOpen_date = DateTime.Now;

            if (isNew)
            {
                _entities.AddTocustomers(cust);
            }

            
            AddToCardlist(true);
            SaveContacts(teek);
            _entities.SaveChanges();

            currentCustomer = cust;
            MessageBox.Show("הרשומה נשמרה בהצלחה", "הודעה", MessageBoxButton.OK);
            secondTab.Visibility = System.Windows.Visibility.Visible;
            if (!(bool)Login.loggedUser.isSuperUser)
                FourthTab.Visibility = System.Windows.Visibility.Hidden;
            else
                FourthTab.Visibility = System.Windows.Visibility.Visible;

        }

        private void SaveContacts(Teek teek)
        {
              foreach (Teek_Contact _contact in contacts)
              {
                  if (_contact.Id == null)
                  {
                      TeekContacts tmpContact = new TeekContacts();
                      tmpContact.is_apotrobs = _contact.Is_aptropos;
                      tmpContact.is_family = _contact.Is_family;
                      tmpContact.is_primary = _contact.Is_primary;
                      tmpContact.address = _contact.Address;
                      tmpContact.contactName = _contact.Name;
                      tmpContact.phone = _contact.Phone;
                      tmpContact.mobile = _contact.Mobile;
                      tmpContact.Teek = teek;
                      _entities.TeekContacts.AddObject(tmpContact);

                  }
                  else
                  {
                      TeekContacts teekContac;
                      int cInt = -1;
                      IQueryable<TeekContacts> tmpcontacts = null;

                      if (Int32.TryParse(_contact.Id, out cInt))
                      {
                          tmpcontacts = (from x in _entities.TeekContacts where x.Id == cInt select x);
                          teekContac = tmpcontacts.First<TeekContacts>();
                          teekContac.is_apotrobs = _contact.Is_aptropos;
                          teekContac.is_family = _contact.Is_family;
                          teekContac.is_primary = _contact.Is_primary;
                          teekContac.address = _contact.Address;
                          teekContac.contactName = _contact.Name;
                          teekContac.phone = _contact.Phone;
                          teekContac.mobile = _contact.Mobile;
                          
                      }
                      

                  }
              }
            
        }

        private void CurrentLocation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (((ComboboxItem)(CurrentLocation.SelectedItem)).Descr == "בית")
            {
                homeChoices.Visibility = System.Windows.Visibility.Visible;
                currLocation.Visibility = System.Windows.Visibility.Hidden;
                currLocationLabel.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                homeChoices.Visibility = System.Windows.Visibility.Hidden;
                if (((ComboboxItem)(CurrentLocation.SelectedItem)).Descr == "שיקום" || ((ComboboxItem)(CurrentLocation.SelectedItem)).Descr == "בית חולים")
                {

                    currLocation.Visibility = System.Windows.Visibility.Visible;
                    currLocationLabel.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }

        private string GetUniqueID()
        {
            string tmpID = string.Empty;
            int lastvalue = 1;
            string teekID = string.Empty;
            formula _formula;

            var formulas = (from x in _entities.formulae where x.bo == "TeekFormula" select x);


            if (formulas.Count<formula>() == 0)
            {
                teekID = lastvalue.ToString("0000");
                _formula = new formula();
                _formula.bo = "TeekFormula";
                _formula.lastvalue = 1;
                _entities.AddToformulae(_formula);

            }
            else
            {
                lastvalue = (formulas.First<formula>()).lastvalue;
                _formula = formulas.First<formula>();
                teekID = (lastvalue + 1).ToString("0000");
                _formula.lastvalue = lastvalue + 1;
            }


            try
            {

                _entities.SaveChanges();
                return "TK" + teekID;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }




        }

        private void Status_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (((ComboboxItem)(Status.SelectedItem)).Descr == "נפטר/ה")
            {
                PassOverLabel.Visibility = System.Windows.Visibility.Visible;
                PassOverDate.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                PassOverLabel.Visibility = System.Windows.Visibility.Hidden;
                PassOverDate.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void Sapak_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Sapak selectedSapak;
            string _type ; 
            selectedSapak = (Sapak)(Sapak.SelectedItem);
            if(selectedSapak != null)
            {
                if (selectedSapak.sapakType == 0)
                    sapakType.Content = "לא מוגדר סוג ספק";
                else
                   if (selectedSapak.sapakType == 1)
                        sapakType.Content = "סוג ספק זמני";
                   else
                       sapakType.Content = "סוג ספק חברה";

                string value = string.Empty;
                if (selectedSapak.methodType == 0)
                    sapakAmount.Content = "לא מוגדת שיטת תשלום";
                    
                else if (selectedSapak.methodType == 1)
                {
                    value = (selectedSapak.Amount).ToString();
                    

                    sapakAmount.Content = string.Format("תשלום חד פעמי בסך : {0} שיקל", value);
                }
                else
                    sapakAmount.Content = string.Format("תשלום בשיטת אחוז  : {0} %", selectedSapak.percentage);

            }
        }

        private Teek CheckIfCustomerExists(string customerNum)
        {
            Teek _teek = null;
            IQueryable<Teek> teeks = null;
           teeks =  _entities.Teeks.Where(x=>x.customer.custNumber == customerNum);
           if (teeks != null)
           {
               if (teeks.Count<Teek>() > 0)
                   _teek = teeks.First<Teek>();

           }

           return _teek;

        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            SearchDocs();
        }

        private void SearchDocs()
        {
            DocsListView.ItemsSource = null;
            IQueryable<TeekDocs> docs = null;
            //Pull all Books
            docs = (from x in _entities.TeekDocs where x.Teek.customer.Id == currentCustomer.Id select x);

            DocsListView.ItemsSource = docs;
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {

        }

        private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var dep = (DependencyObject)e.OriginalSource;
            while ((dep != null) && !(dep is ListViewItem))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep == null)
                return;
            currentDoc = ((TeekDocs)DocsListView.ItemContainerGenerator.ItemFromContainer(dep));
            try
            {
                System.Diagnostics.Process.Start(currentDoc.docPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            TeekDocs doc = new TeekDocs();
            FileInfo file = null ;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            bool? userClickedOK = openFileDialog1.ShowDialog();
            if (userClickedOK == true)
            {
                file = new FileInfo(openFileDialog1.FileName);
                doc.docName = file.Name;
                doc.docPath = file.FullName;
                doc.update_dt = DateTime.Now;
                doc.creation_dt = DateTime.Now;
                doc.createdBy = "yosef";
                doc.Teek = currentCustomer.Teek;
                switch (file.Extension)
                {
                    case ".xlsx": doc.docType = "Excel File"; break;
                    case ".xls": doc.docType = "Excel File"; break;
                    case ".docx": doc.docType = "Word File"; break;
                    case ".doc": doc.docType = "Word File"; break;
                    case ".pdf": doc.docType = "PDF File"; break;
                    case ".txt": doc.docType = "Text File"; break;
                    default: doc.docType = "Generic File"; break;
                }

                try
                {
                    _entities.AddToTeekDocs(doc);
                    _entities.SaveChanges();
                    SearchDocs();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }

        private void onClose_Click(object sender, RoutedEventArgs e)
        {

            if (CloseOpenTeek.Content == FindResource("Close"))
            {

                MessageBoxResult result = MessageBox.Show("לגור את התיק ?", "הודעה", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    mainTab.IsEnabled = false;
                    currentCustomer.Teek.status = "4";
                    currentCustomer.Teek.status_descr = "סגור";
                    _entities.SaveChanges();
                }
                CloseOpenTeek.Content = FindResource("Open");
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("פתוח את התיק ?", "הודעה", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    mainTab.IsEnabled = true;
                    currentCustomer.Teek.status = "2";
                    currentCustomer.Teek.status_descr = "בטיפול";
                    _entities.SaveChanges();
                }
                CloseOpenTeek.Content = FindResource("Close");
            }



            
        }

        #region Contacts
       
        private bool AddToCardlist(bool isSave)
        {

            if (isSave)
            {
                if (string.IsNullOrWhiteSpace(card.Nurse1.Value) && string.IsNullOrWhiteSpace(card.Phoen1.Value) && string.IsNullOrWhiteSpace(card.Phoen2.Value) && string.IsNullOrWhiteSpace(card.Address.Text))
                    return true;
            }


            if (string.IsNullOrWhiteSpace(card.Nurse1.Value))
            {
                MessageBox.Show("שם איש קשר הינו חובה", "שגיאה", MessageBoxButton.OK);
                return false;
            }

            if (card.IsAddedToList == true)
            {
                contacts[currentContactCard].Name = card.Nurse1.Value;
                contacts[currentContactCard].Phone = card.Phoen1.Value;
                contacts[currentContactCard].Mobile = card.Phoen2.Value;
                contacts[currentContactCard].Address = card.Address.Text;
                contacts[currentContactCard].Is_primary = (bool)card.primary.IsChecked;
                contacts[currentContactCard].Is_family = (bool)card.family.IsChecked;
                contacts[currentContactCard].Is_aptropos = (bool)card.aptrops.IsChecked;
                contacts[currentContactCard].Is_synched = true;
            }
            else
            {
                Teek_Contact tmpContact = new Teek_Contact();
                tmpContact.Name = card.Nurse1.Value;
                tmpContact.Phone = card.Phoen1.Value;
                tmpContact.Mobile = card.Phoen2.Value;
                tmpContact.Address = card.Address.Text;
                tmpContact.Is_primary = (bool)card.primary.IsChecked;
                tmpContact.Is_family = (bool)card.family.IsChecked;
                tmpContact.Is_aptropos = (bool)card.aptrops.IsChecked;
                tmpContact.Id = null;
                tmpContact.Is_synched = true;
                contacts.Add(tmpContact);
            }
            return true;

        }

        private void ClearCard()
        {
            card.Nurse1.Value = string.Empty;
            card.Phoen1.Value = string.Empty;
            card.Phoen2.Value = string.Empty;
            card.Address.Text = string.Empty;
            card.primary.IsChecked = false;
            card.family.IsChecked = false;
            card.aptrops.IsChecked = false;
            card.IsAddedToList = false;


        }

        private void SetCard(Teek_Contact _tmpcard)
        {
            card.Nurse1.Value = _tmpcard.Name;
            card.Phoen1.Value = _tmpcard.Phone;
            card.Phoen2.Value = _tmpcard.Mobile;
            card.Address.Text = _tmpcard.Address;
            card.primary.IsChecked = _tmpcard.Is_primary;
            card.family.IsChecked = _tmpcard.Is_family;
            card.aptrops.IsChecked = _tmpcard.Is_aptropos;
            card.IsAddedToList = _tmpcard.Is_synched;
        }
        private void DeleteContact(object sender, MouseEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("האם אתה בטוח שרוצה למחוק איש קשר זה ?", "אזהרה", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.No) return;
            else
            {
                if (contacts[currentContactCard].Id == null)
                    contacts.Remove(contacts[currentContactCard]);
                else
                {
                    TeekContacts teekContac;
                    int index = -1;
                    IQueryable<TeekContacts> docs = null;
                    if (Int32.TryParse(contacts[currentContactCard].Id, out index))
                    {
                        try
                        {
                            docs = (from x in _entities.TeekContacts where x.Id == index select x);
                            teekContac = docs.First<TeekContacts>();
                            _entities.TeekContacts.DeleteObject(teekContac);

                            contacts.Remove(contacts[currentContactCard]);

                            if (contacts.Count > 0)
                            {
                                if (currentContactCard == 0)
                                {
                                    ++currentContactCard;
                                    SetCard(contacts[currentContactCard]);
                                }
                                else
                                {
                                    --currentContactCard;
                                    SetCard(contacts[currentContactCard]);
                                }
                            }
                            else
                                ClearCard();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                        }
                    } 
                }
            }
        }
        private void AddContactEnter(object sender, MouseButtonEventArgs e)
        {
           if(AddToCardlist( false) )
                 ClearCard();
        }
        #endregion

        private void GetPreviouseContact(object sender, MouseButtonEventArgs e)
        {
            if (currentContactCard == -1)
            {
                MessageBox.Show("אין עוד אנשי קשר ", "הודעה", MessageBoxButton.OK);
                return;
            }
            else
            {
                --currentContactCard;
                if (currentContactCard  == -1 )
                {
                    MessageBox.Show("אין עוד אנשי קשר ", "הודעה", MessageBoxButton.OK);
                    ++currentContactCard;
                    return;
                }
                else
                    SetCard(contacts[currentContactCard]);
                SetCard(contacts[currentContactCard]);
            }
        }

        private void GetNextContact(object sender, MouseButtonEventArgs e)
        {
            if (currentContactCard > (contacts.Count -1) )
            {
                MessageBox.Show("אין עוד אנשי קשר ", "הודעה", MessageBoxButton.OK);
                return;
            }
            else
            {
 
                    ++currentContactCard;
                    if (currentContactCard > (contacts.Count - 1))
                    {
                        MessageBox.Show("אין עוד אנשי קשר ", "הודעה", MessageBoxButton.OK);
                        --currentContactCard;
                        return;
                    }
                    else
                    SetCard(contacts[currentContactCard]);
               
            }
        }

        #region Finnicial
        private void AddFinButton_Click(object sender, RoutedEventArgs e)
        {
            AddSource source = new AddSource(currentCustomer.Teek);
            source.Show();
        }

        private void SearchFinButton_Click(object sender, RoutedEventArgs e)
        {
            PerformSearch();


        }
        public void PerformSearch()
        {
            IQueryable<PaymentHeader> paymentHeaders = null;

            paymentHeaders = (from x in _entities.PaymentHeaders where x.Teek.Id == currentCustomer.Teek.Id  select x);

            if (FinSource.GotValue)
                paymentHeaders = paymentHeaders.Where(DynamicExpressions.GetWhereCond<PaymentHeader>(FinSource.FieldID, "Contains", FinSource.Value));
            FinListView.ItemsSource = paymentHeaders;
        }

        private void ClearFinButton_Click(object sender, RoutedEventArgs e)
        {
            FinSource.Value = string.Empty;
        }
        #endregion

        private void OnSourceMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var dep = (DependencyObject)e.OriginalSource;
            while ((dep != null) && !(dep is ListViewItem))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep == null)
                return;
            currentPaymentHeader = (PaymentHeader)FinListView.ItemContainerGenerator.ItemFromContainer(dep);
            AddSource _addsource = new AddSource(currentCustomer.Teek, currentPaymentHeader);
            _addsource.Show();
        }

    

        private void Hyperlink_RequestSourceNavigate(object sender, RequestNavigateEventArgs e)
        {
            
        }

    }
    internal class ComboboxItem
    {
        string id;
        string descr;


        public ComboboxItem()
        {
        }
        public ComboboxItem(string _id, string _descr)
        {
            id = _id;
            descr = _descr;
        }
        public string Id
        {
            get { return id; }
            set { id = value; }
        }


        public string Descr
        {
            get { return descr; }
            set { descr = value; }
        }

    }

    public class Teek_Contact
    {
        string id;

        string name;
        string address;
        string phone;
        string mobile;
        bool is_primary;
        bool is_family;
        bool is_aptropos;
        bool is_synched;


 

        public Teek_Contact()
        {
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
        public string Phone
        {
            get { return phone; }
            set { phone = value; }
        }
        public string Mobile
        {
            get { return mobile; }
            set { mobile = value; }
        }
        public bool Is_primary
        {
            get { return is_primary; }
            set { is_primary = value; }
        }
        public bool Is_family
        {
            get { return is_family; }
            set { is_family = value; }
        }
        public bool Is_aptropos
        {
            get { return is_aptropos; }
            set { is_aptropos = value; }
        }

        public bool Is_synched
        {
            get { return is_synched; }
            set { is_synched = value; }
        }
    }
}
